package com.passwordmanager.manager;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.passwordmanager.data.Account;
import com.passwordmanager.data.Password;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
	private static final String DATABASE_NAME = "passwordmanager.sqlite";
	private static final int DATABASE_VERSION = 6;
	
	private Dao<Account, Integer> accountDao;
	private Dao<Password, Integer> passwordDao;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connection) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connection, Password.class);
			TableUtils.createTable(connection, Account.class);
		} catch(SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connection, int oldVer,
			int newVer) {
		try {
			TableUtils.dropTable(connection, Password.class, true);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new " + newVer, e);
		}
	}

	public Dao<Password, Integer> getPasswordDao() throws SQLException {
		if (passwordDao == null) {
			passwordDao = getDao(Password.class);
		}
		return passwordDao;
	}
	
	public Dao<Account, Integer> getAccountDao() throws SQLException {
		if (accountDao == null) {
			accountDao = getDao(Account.class);
		}
		
		return accountDao;
	}
	
	 @Override
	 public void close() {
	    super.close();

	    accountDao = null;
	    passwordDao = null;
	 }

}
